package com.example.codereview.git;

import com.example.codereview.util.JOptionPaneUtils;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.storage.file.FileRepositoryBuilder;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;

public class JgitUtil {

    public static Git openRpo(String localPath) {
        Git git = null;
        try {
            File file = Paths.get(localPath, ".git").toFile();
            if(!file.exists()){
                JOptionPaneUtils.warn("该项目没有git实例化！");
            }
            Repository repository = new FileRepositoryBuilder()
                    .setGitDir(file)
                    .build();
            git = new Git(repository);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return git;
    }

    private static File gitFile(String localPath){
        File file = Paths.get(localPath, ".git").toFile();
        if(!file.exists()){
            if(localPath.contains("/")) {
                String substring = localPath.substring(0, localPath.lastIndexOf("/"));
                return gitFile(substring);
            }
        }
        return file;
    }

    public static Git openRpoPlus(String localPath) {
        Git git = null;
        try {
            File file = gitFile(localPath);
            Repository repository = new FileRepositoryBuilder()
                    .setGitDir(file)
                    .build();
            git = new Git(repository);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return git;
    }

}